import os
import sys
from configparser import ConfigParser
from data_store.db_connection_pool import SqlitePool
from util.decorator import singleton


@singleton
class SqliteApi(SqlitePool):
    def __init__(self):
        self.base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
        self.sqlite_config = self.get_sqlite_config()
        super().__init__(self.sqlite_config['database'],
                         max_usage=self.sqlite_config['max_usage'],
                         closeable=self.sqlite_config['closeable'])

    def get_sqlite_config(self):
        conf = ConfigParser()
        # conf.read(os.path.join(self.base_path, 'config/config.ini'))
        conf.read('/Users/fengwensen/projects/code_analysis/config/config.ini')
        return conf['sqlite']

    def create_table(self, table_name):
        create_table_query = f"""
        CREATE TABLE IF NOT EXISTS {table_name} (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            encryption INTEGER,
            decryption INTEGER,
            signature INTEGER,
            verification INTEGER,
            hash INTEGER,
            algorithm TEXT,
            analysis TEXT,
            code  TEXT
        );
        """
        result, error = self.run_query(create_table_query)
        return result, error

    def find_all_by_table(self, table):
        sql = f'SELECT * FROM {table};'
        result, error = self.run_query(sql)
        return result, error

    # 插入一条数据
    def insert_one_record(self, data):
        encryption = data['encryption']
        decryption = data['decryption']
        signature = data['signature']
        verification = data['verification']
        hash_ = data['hash']
        algorithm = data['algorithm'] if data['algorithm'] else 'null'
        analysis = data['analysis'] if data['analysis'] else 'null'
        code = data['code'] if data['code'] else 'null'
        sql = f"""INSERT INTO code_analysis_results (encryption, decryption, signature, verification, hash, algorithm, analysis, code)
        VALUES ({encryption},{decryption},{signature}, {verification}, {hash_}, '{algorithm}','{analysis}','{code}');""".format(
            encryption=encryption,
            decryption=decryption,
            signature=signature,
            verification=verification,
            hash_=hash_,
            algorithm=algorithm,
            code=code

        )
        result, error = self.run_query(sql)
        return result, error

    # 删除一条数据
    def delete_one(self, id):
        sql = f"""delete from code_analysis_results where id={id}""".format(id=id)
        result, error = self.run_query(sql)
        return result, error


if __name__ == '__main__':
    sqlite_api = SqliteApi()
    res = sqlite_api.find_all_by_table("code_analysis_results")
    print(res)

    res = sqlite_api.delete_one('26')
    print(res)

    # res = sqlite_api.insert_one_record()
    # print(res)
